package epoch.game.core.timer;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

import epoch.game.core.common.Loggers;
import epoch.game.core.thread.ServerThread;

public class FixedRateServerTimerTask implements Runnable {

	protected ServerThread serverThread;
	
	protected List<GameTimer> timers = new LinkedList<GameTimer>();
	
	protected ScheduledFuture<?> scheduledFuture;
	
	public FixedRateServerTimerTask(ServerThread serverThread){
		this.serverThread = serverThread;
	}
	
	protected volatile boolean stoped = true;
	
	@Override
	public void run() {
		if (stoped) {
			return;
		}
		long nowTime = System.currentTimeMillis();
		int repeat = 0;
		try {
			synchronized (timers) {
				Iterator<GameTimer> iterator = timers.iterator();
				while (iterator.hasNext()) {
					GameTimer timer = iterator.next();
					if(timer.isCanceled()){
						iterator.remove();
						continue;
					}
					repeat = timer.getRepeat();
					if (repeat == -1 || repeat > 0) {
						if (timer.getDelay() > 0) {
							timer.setNextActionTime(nowTime + timer.getDelay());
							timer.setDelay(0);
						}
						if (nowTime > timer.getNextActionTime()) {
							if (repeat > 0) {
								timer.setRepeat(--repeat);
							}
							if (timer.priority) {
								serverThread.addAction(timer);
							} else {
								serverThread.addTimerAction(timer);
							}
							timer.setNextActionTime(nowTime + timer.getPeriod());
						}
					}
					if (repeat == 0) {
						iterator.remove();
					}
				}
			}
		} catch (Throwable ex) {
			Loggers.CORE_LOGGER.error("定时任务线程出错：thread=" + Thread.currentThread().getName() + ",ex=" + ex, ex);
		}
	}


	/**
	 * 添加定时器
	 * @param timer
	 */
	public void addTimer(GameTimer timer){
		synchronized (timers) {
			if(!timers.contains(timer)){
				if(timer.priority){
					this.timers.add(0,timer);
				}else{
					this.timers.add(timer);
				}				
			}
		}		
	}
	
	public void removeTimer(GameTimer timer){
		synchronized (timers) {
			this.timers.remove(timer);
		}
	}
	
	/**
	 * 开始执行定任务
	 */
	public void start(){
		if(!stoped){
			return;
		}
		stoped = false;
		scheduledFuture = ServerTimerManager.getInstance().scheduleAtFixedRate(this, 0L, this.serverThread.getHeart());
	}
	
	/**
	 * 取消定时任务的执行
	 * 
	 * @param force
	 */
	public void cancel(boolean force){
		stoped = true;
		if(scheduledFuture!=null){
			scheduledFuture.cancel(force);
		}
	}	
}
